package com.example.gcm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.gcm.connectserver.JSONParser;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class getAllAccountsService extends IntentService
{

	// Creating JSON Parser object
	JSONParser jParser = new JSONParser();

	ArrayList<HashMap<String, Object>> accountsList;

	// url to get all products list
	private static String url_all_accounts = "http://10.0.2.2/gcm_server/get_all_accounts.php";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_ACCOUNT = "accounts";
	private static final String TAG_NAME = "name";
	private static final String TAG_PHONE = "phone";
	private static final String TAG_REGID = "regid";
	private static final String TAG_DATASEND = "datasend";

	// products JSONArray
	JSONArray accounts = null;
		
	public getAllAccountsService(String name) 
	{
		super(name);
	}
	
	public getAllAccountsService() 
	{
		super("Tuan android");
	}

	@Override
	protected void onHandleIntent(Intent intent) 
	{
		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// getting JSON string from URL
		JSONObject json = jParser.makeHttpRequest(url_all_accounts, "GET", params);
					
		// Check your log cat for JSON reponse
		Log.d("All Accounts: ", json.toString());

		try 
		{
			// Checking for SUCCESS TAG
			int success = json.getInt(TAG_SUCCESS);

			if (success == 1) 
			{
					// products found
					// Getting Array of Products
					accounts = json.getJSONArray(TAG_ACCOUNT);
					accountsList = new ArrayList<HashMap<String,Object>>();

					// looping through All Products
					for (int i = 0; i < accounts.length(); i++) 
					{
						JSONObject c = accounts.getJSONObject(i);

						// Storing each json item in variable
						String phone = c.getString(TAG_PHONE);
						String name = c.getString(TAG_NAME);
						String regId = c.getString(TAG_REGID);

						// creating new HashMap
						HashMap<String, Object> map = new HashMap<String, Object>();

						// adding each child node to HashMap key => value
						map.put(TAG_PHONE, phone);
						map.put(TAG_NAME, name);
						map.put(TAG_REGID, regId);

						// adding HashList to ArrayList
						accountsList.add(map);
							
					}
					
					Intent broadcast = new Intent();
					broadcast.putExtra(TAG_DATASEND, accountsList);
					broadcast.setAction("ACCOUNTS_RECEIVER");
					getBaseContext().sendBroadcast(broadcast);
			}	
					
		} 
		
		catch (JSONException e) 
		{
			e.printStackTrace();
		}
	}
	

}
